package com.sihan.framework.etm.common.util;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.sihan.framework.etm.entity.MailAndSmsLog;
import com.sihan.framework.etm.mapper.MailAndSmsLogMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 短信重试发送
 * @author 张荣英
 * @date Aug 5, 2019 5:44:05 PM
 */
@Slf4j
public class AliSMSSendTask implements Runnable {
	
	private final IAcsClient client;
	private final SendSmsRequest request;
	private int resendTimes;
	private final int resendInterval;
	@Autowired
	private MailAndSmsLogMapper mailAndSmsLogMapper;
	
	AliSMSSendTask(IAcsClient client, SendSmsRequest request, int resendTimes, int resendInterval, MailAndSmsLogMapper mailAndSmsLogMapper){
		this.client = client;
		this.request = request;
		this.resendTimes = resendTimes;
		this.resendInterval = resendInterval;
		this.mailAndSmsLogMapper = mailAndSmsLogMapper;
	}
	@Override
	public void run() {
		Long id = null;
		try{
			//默认发送消息失败
			id = persistentModel((short) 0);
		}catch(Exception e){
			log.error("保存日志出错",e);
		}
		Exception e = null;
		while(resendTimes>0){
			try {
				SendSmsResponse response =  client.getAcsResponse(request);
				log.info(response.getCode()+"====>"+response.getMessage());
					try{
						updateModel((short) 1,id);
					}catch(Exception ue){
						log.error("更新日志出错",e);
					}
					break;
			} catch (Exception ee) {
				e=ee;
				resendTimes--;
				log.error("保存日志出错",e);
			}
			try {
				Thread.sleep(resendInterval);
			} catch (InterruptedException ie) {
				log.error("线程休眠出错",e);
				Thread.currentThread().interrupt();
			}
			if(resendTimes<1){
				log.error(String.format("发送短信:\"%s\",内容：\"%s\",已经重试3次，发送失败，请尽快检查原因，详细异常如下：",request.getPhoneNumbers(),request.getTemplateCode()+"-"+request.getTemplateParam()),e);
			}
		}
	}
	
	public Long persistentModel(short isSuccess){
		Date now = new Date();
		MailAndSmsLog log = new MailAndSmsLog();
		log.setPhoneOrMail(request.getPhoneNumbers());
		log.setSubject(request.getTemplateCode());
		log.setContent(request.getTemplateParam());
		log.setSendDate(now);
		log.setType((short) 1);
		log.setIsSuccess(isSuccess);
		mailAndSmsLogMapper.insert(log);
		return log.getId();
	}
	
	public void updateModel(short isSuccess,Long id) {
		MailAndSmsLog log = mailAndSmsLogMapper.selectById(id);
		log.setIsSuccess(isSuccess);
		mailAndSmsLogMapper.updateById(log);
	}
}
